<template>
    <div class="danmu-container" ref="containerRef">
        <div v-for="(danmu, index) in activeDanmus" :key="danmu.id" class="danmu-item" :style="danmu.style">
            {{ danmu.content }}
        </div>
        <div class="send-btn">
            <input v-model="content" type="text" placeholder="请留下你的足迹..." @keyup.enter="sendDanmu">
            <button @click="sendDanmu">发送</button>
        </div>
    </div>
    <CommentView :moduleId="moduleId" :title="title"></CommentView>
</template>

<script setup>
import { ref, onMounted, onUnmounted, reactive } from 'vue';
import { findGuestbookList, addGuestbook } from '@/api/guestbook';
import { findCommentPageList } from '@/api/comment.js';
import CommentView from './CommentView.vue';
import { message } from 'ant-design-vue';
// 弹幕列表
const DEFAULT_DANMU = ref([]);
const containerRef = ref(null);
const activeDanmus = ref([]);
let animationFrameId = null;

// 模块ID
const moduleId = ref('1');
const title = ref('评论区');
// 发送的弹幕内容
const content = ref('');
// 生成随机数
const random = (min, max) => Math.random() * (max - min) + min;

// 创建弹幕对象 - 确保初始位置合理，立即显示
const createDanmu = (content, index) => {
    const duration = 8 + random(0, 8); // 8-16秒随机速度
    const topPercent = random(5, 95);  // 垂直位置随机
    const fontSize = Math.floor(random(14, 20)); // 随机字体大小
    // 关键修改：初始延迟改为0到2秒，避免过长等待
    const delay = Math.min(index * 0.1, 0); // 最大延迟不超过2秒

    return {
        id: Date.now() + index,
        content,
        style: {
            top: `${topPercent}%`,
            animationDelay: `${delay}s`, // 缩短延迟时间
            animationDuration: `${duration}s`,
            right: '-50%', // 初始位置在右侧边缘外一点点
            fontSize: `${fontSize}px`,
        },
        duration
    };
};

// 初始化弹幕
const initDanmus = () => {
    activeDanmus.value = DEFAULT_DANMU.value.map((content, index) =>
        createDanmu(content, index)
    );
};

// 循环检测弹幕位置并重置
const loopDanmus = () => {
    if (!containerRef.value) return;

    const danmuElements = containerRef.value.querySelectorAll('.danmu-item');

    danmuElements.forEach((el, index) => {
        const rect = el.getBoundingClientRect();

        // 如果弹幕完全移出屏幕左侧
        if (rect.right <= 0) {
            // 重置位置到右侧
            el.style.right = '-100%';

            // 设置新的随机垂直位置
            const newTop = random(5, 95);
            el.style.top = `${newTop}%`;

            // 随机化动画速度
            const duration = 8 + random(0, 8);
            el.style.animationDuration = `${duration}s`;

            // 随机化字体大小
            const fontSize = Math.floor(random(14, 20));
            el.style.fontSize = `${fontSize}px`;

            // 重置时无延迟，立即开始动画
            el.style.animationDelay = '0s';

            // 强制重绘，触发动画重新开始
            void el.offsetWidth;
            el.style.animation = 'none';
            void el.offsetWidth; // 触发重绘
            el.style.animation = `scrollDanmu linear ${duration}s infinite`;
        }
    });

    animationFrameId = requestAnimationFrame(loopDanmus);
};
// 发送弹幕
const sendDanmu = async () => {
  if (!localStorage.getItem('token')) {
    message.error('请先登录');
    return;
  }
    let form = {
        moduleId: moduleId.value,
        content: content.value,
    };
    await addGuestbook(form).then(res => {
        if (res.code === 200 && res.data) {
            message.success('发送成功');
            DEFAULT_DANMU.value.push(content.value);
            // 创建新弹幕对象并添加到活跃列表
            const newDanmu = createDanmu(content.value, activeDanmus.value.length);
            activeDanmus.value.push(newDanmu);
            content.value = '';
        }
    })
};
// 获取弹幕列表
const getGuestbookList = async () => {
    await findGuestbookList({ moduleId: '1' }).then(res => {
        if (res.code == 200) {
            DEFAULT_DANMU.value = res.data.map(e => e.content);
        }
    }).catch(err => { })
};

onMounted(async () => {
    await getGuestbookList();
    initDanmus();
    // 移除nextTick等待，直接启动动画
    loopDanmus();
});

onUnmounted(() => {
    if (animationFrameId) {
        cancelAnimationFrame(animationFrameId);
    }
});
</script>

<style scoped lang="less">
.danmu-container {
    position: relative;
    width: 100%;
    height: 100vh;
    overflow: hidden;
    background-image: url('@/assets/img/emoji-emoticons.jpg');
    background-size: cover;
    background-position: center;
}

.send-btn {
    position: absolute;
    left: 50%;
    top: 50%;
    width: 321px;
    height: 40px;
    margin-left: -160.5px;
    margin-top: -20px;

    input {
        border-radius: 30px;
        height: 40px;
        border: 1px solid #fff;
        background-color: transparent;
        margin-right: 10px;
        outline: none;
        padding: 8px 12px;
        color: #fff;

    }

    ::placeholder {
        color: #fff;
        opacity: 1;
    }

    button {
        border-radius: 30px;
        height: 40px;
        background-color: transparent;
        color: #fff;
        border: 1px solid #fff;
        width: 70px;
        cursor: pointer;

        &:hover {
            color: #fff;
            border-color: #fff;
        }
    }
}

/* 单个弹幕样式：绝对定位 + 动画从右到左 */
.danmu-item {
    position: absolute;
    white-space: nowrap;
    color: #fff;
    font-weight: bold;
    padding: 6px 12px;
    background: rgba(0, 0, 0, 0.6);
    border-radius: 20px;
    animation: scrollDanmu linear infinite;
    box-sizing: border-box;
}

/* 关键帧：加快进入速度，减少初始等待 */
@keyframes scrollDanmu {
    from {
        right: -50%;
        /* 起始位置更靠近屏幕，减少进入时间 */
        opacity: 0;
    }

    5% {
        opacity: 1;
        /* 快速显示 */
    }

    to {
        right: 100%;
        opacity: 0;
    }
}
</style>